package lium.lbs.lbsim.activity

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.model.UserInfo
import cn.jpush.im.api.BasicCallback
import com.buz.hjcdriver.bean.LoginResultBean
import com.lmlibrary.Constants
import lium.lbs.lbsim.utils.UserUtils
import lium.lbs.lbsim.R
import com.lmlibrary.bean.ResponseBean
import lium.lbs.lbsim.utils.callbck.DialogCallback
import lium.lbs.lbsim.utils.ToastUtils
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_login.*
import lium.lbs.lbsim.jchat.utils.SharePreferenceManager
import lium.lbs.lbsim.jgchat.database.UserEntry
import lium.lbs.lbsim.jgchat.utils.photovideo.takevideo.utils.LogUtils
import java.util.HashMap
import lium.lbs.lbsim.utils.SpUtils


class LoginActivity : BaseActivity() {
    private var isLogin: Boolean = false
    private var mMyInfo: UserInfo? = null
    //退出时的时间
    private var mExitTime: Long = 0
    private var exitTime: Long = 0

    override fun getLayoutId(): Int {
        return R.layout.activity_login
    }

    override fun initView(savedInstanceState: Bundle?) {
        addOnClickListeners(R.id.login_toregist, R.id.btn_start_login, R.id.login_agreenment, R.id.forgetpassword)
        if (!TextUtils.isEmpty( SpUtils.getInstance().get(Constants.memberId, "").toString()) &&!TextUtils.isEmpty( SpUtils.getInstance().get(Constants.phonepw, "").toString())){
            login_phone.setText(SpUtils.getInstance().get(Constants.phone, "").toString())
            login_pwd.setText(SpUtils.getInstance().get(Constants.phonepw, "").toString())

        }



    }

    public override fun onResume() {
        super.onResume()

        LogUtils.e(
            "body--memberId--" + SpUtils.getInstance().get(
                Constants.memberId,
                ""
            ).toString() + "--phonepw--" + SpUtils.getInstance().get(Constants.phonepw, "").toString()
        )


    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v!!.id) {
            R.id.login_toregist -> {
                val intent = Intent(this@LoginActivity, RegistActivity::class.java)
                startActivity(intent)
                finish()
            }
            R.id.btn_start_login -> {
                login()
            }
            R.id.forgetpassword -> {
                val intent = Intent(this, RegistActivity::class.java)
                intent.putExtra("isforget", true)
                startActivity(intent)
                finish()
            }
            R.id.login_agreenment -> {
                val intent = Intent(this, WebViewActivity::class.java)
                intent.putExtra("title", "服务条款")
                intent.putExtra("url", Constants.lawareenment)
                startActivity(intent)
            }
            R.id.btn_start_login -> {
                login()
            }

        }
    }

    fun login() {
        if (TextUtils.isEmpty(login_phone.text.toString()) ||
            login_phone.text.toString().length != 11
        ) {
            ToastUtils.showToast("手机号码无效")
            return
        }

        if (TextUtils.isEmpty(login_pwd.text.toString())) {
            ToastUtils.showToast("密码无效")
            return
        }
        val param = HashMap<String, String>()
        param["phone"] = login_phone.text.toString()
        param["deviceType"] = "android"
        param["password"] = login_pwd.text.toString()

        param["deviceId"] = ""
        param["deviceName"] = ""

        postData("/authorize", param, object : DialogCallback<ResponseBean<LoginResultBean>>(this) {
            override fun onSuccess(response: Response<ResponseBean<LoginResultBean>>) {
                SpUtils.getInstance().put(Constants.phone, login_phone.text.toString())
                SpUtils.getInstance().put(Constants.phonepw, login_pwd.text.toString())

                loginJIM(response.body().data.memberId, login_pwd.text.toString())
            }
        })
    }

    fun loginJIM(memberId: String, password: String) {
        JMessageClient.login(memberId, "123456", object : BasicCallback() {
            override fun gotResult(responseCode: Int, responseMessage: String) {
                if (responseCode == 0) {
                    mMyInfo = JMessageClient.getMyInfo();
                    LogUtils.e(
                        "myTest-LoginActivity-getAppKey--" + mMyInfo?.getAppKey() + "--getNickname--" + mMyInfo?.getNickname() +
                                "--getUserID--" + mMyInfo?.getUserID() + "--getUserName--" + mMyInfo?.getUserName()
                    )

                    SharePreferenceManager.setCachedPsw(password)
                    val myInfo = JMessageClient.getMyInfo()
                    val avatarFile = myInfo.avatarFile
                    //登录成功,如果用户有头像就把头像存起来,没有就设置null
                    if (avatarFile != null) {
                        SharePreferenceManager.setCachedAvatarPath(avatarFile.absolutePath)
                    } else {
                        SharePreferenceManager.setCachedAvatarPath(null)
                    }
                    val username = myInfo.userName
                    val appKey = myInfo.appKey
                    LogUtils.e("myTest-" + username)

                    var user = UserEntry.getUser(username, appKey)
                    if (null == user) {
                        user = UserEntry(username, appKey)
                        user.save()
                    }
                    UserUtils.login(memberId + "")
                    SpUtils.getInstance().put(Constants.isLogin, true)
                    val intent = Intent(this@LoginActivity, lium.lbs.lbsim.activity.MainActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
                    startActivity(intent)
                    finish()
                } else {
                    ToastUtils.showToast("登录失败$responseMessage")
                }
            }
        })
    }



    // 再按一次退出程序
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(applicationContext, "再按一次退出程序", Toast.LENGTH_SHORT).show()
                exitTime = System.currentTimeMillis()
            } else {
                finish()
                System.exit(0)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun getNetWorkData() {

    }

}
